<template>
  <span class="app-clock">
    {{ time | date(formatter, locale) }}<br />
    <!-- {{ formattedTime }} -->
  </span>
</template>

<script>
import format from "../utils/date-formatter";

export default {
  props: {
    formatter: {
      type: String,
    },

    locale: Object,
  },
  data() {
    return {
      time: Date.now(),
    };
  },

  computed: {
    formattedTime() {
      return format(this.time, this.formatter, this.locale);
    },
  },
  mounted() {
    // 1.初始化计时器
    this.initTimer();
    // 2. todo somthings...
  },

  watch: {
    time: function (newTime) {
      if (Number.parseInt(newTime / 1000) % 60 === 0) {
        this.$emit("hour-change", new Date(newTime));
      }
    },
  },

  methods: {
    initTimer() {
      this.timer = setInterval(() => {
        this.time = Date.now();
      }, 1000);
    },

    clearTimer() {
      clearInterval(this.timer);
    },
  },

  beforeDestroy() {
    // 1.清理计时器
    this.clearTimer();
    // 2.clear somthings...
  },
};
</script>

<style lang="scss" scoped>
.app-clock {
  color: #fff;
}
</style>
